
% interp_factor   : 插值数量
% method          : 插值方式:
%                     repelem : 重复数据插值
%                     fir     : fir滤波器插值
% raw_data_buf    : 原始数据
% raw_fs          : 原始采样频率
% plot_en         : 是否开启数字DAC输出波形

function [bitstream,vout,interp_data] = sigma_delta_dac_top(raw_data_buf,param_cfg)

% addpath([param_cfg.addpath_str.root_path,param_cfg.addpath_str.str1       ]);
% addpath([param_cfg.addpath_str.root_path,param_cfg.addpath_str.str2       ]);
% addpath([param_cfg.addpath_str.root_path,param_cfg.addpath_str.str3       ]);
% addpath([param_cfg.addpath_str.root_path,param_cfg.addpath_str.str4       ]);
% addpath([param_cfg.addpath_str.root_path,param_cfg.addpath_str.str5       ]);
% addpath([param_cfg.addpath_str.root_path,param_cfg.addpath_str.str6       ]);
% addpath([param_cfg.addpath_str.root_path,param_cfg.addpath_str.str7       ]);

    interp_factor   = param_cfg.sdm.osr                 ;
    method          = param_cfg.sdm.method              ;
    raw_fs          = param_cfg.raw_data_cfg.raw_fs     ;
    bitlevel        = param_cfg.sdm.bitlevel            ;
    order           = param_cfg.sdm.order               ;
    vref_val        = param_cfg.sdm.vref_val            ;
    miss_en         = param_cfg.sdm.miss_en             ;
    shap_en         = param_cfg.sdm.shap_en             ;
    msh_level       = param_cfg.sdm.msh_level           ;

    plot_en         = param_cfg.debug.sdm_plot_en       ;

    fixed_point_cfg = param_cfg.fixed_point_cfg         ;
    gwn_en          = param_cfg.sdm.gwn_en              ;

    sdm_gain = 1.0519;
    %% Sigma-Delta DAC 主控流程框架
    % 假设已加载 audio_data，fs 为采样率

    vref = fixed_point_calculation_vector(vref_val , 1, 'mul' , fixed_point_cfg.Int_num , fixed_point_cfg.Fixed_num,fixed_point_cfg.DataType);

    % ========== Step 1: 插值模块 ==========
    %clc;
    fprintf("正在增采样插值,OSR=%d.\n",interp_factor);
    interp_data = interpolate_raw(raw_data_buf, interp_factor, method,param_cfg);



    % ========== Step 2: 初始化 ==========
    interp_data_length = length(interp_data);      % 插值后总样本数
    bitstream = zeros(interp_data_length, 1);      % 存储1-bit输出

    % ========== Step 3: SD调制 ==========
    if(order == "1th")    %1阶
        bitstream = nth_order_sigma_delta(interp_data,bitlevel,vref,1);
    else
        if(order == "2th")  %2阶
            bitstream = nth_order_sigma_delta(interp_data,bitlevel,vref,2);
        else                      %3阶
            if(order == "3th")
                bitstream = third_order_sigma_delta_cifb(interp_data,bitlevel,vref);
            else                    % 4阶
                if(order == "4th order ciff")
                    bitstream = fourth_order_sigma_delta_ciff(interp_data,bitlevel,vref,param_cfg);
                else
                    error ("SD调制器选择错误!");
                end
            end
        end
    end

    bitstream = fixed_point_calculation_vector(bitstream , 1, 'mul' , fixed_point_cfg.Int_num , fixed_point_cfg.Fixed_num,fixed_point_cfg.DataType);



    %% 添加失配/失配整形
    %clc;
    fprintf("正在执行失配整形\n");
    ms_out = mismatch_shaping(bitstream ,bitlevel, miss_en ,shap_en,msh_level,'enable','d');
    plotPowerSpectrum(ms_out,2^16,48000,64,'MMS1');
    %%  码流归一化
    ms_out = ms_out / (2^(bitlevel-1)-1);
    bitstream = bitstream /  (2^(bitlevel-1));
    plotPowerSpectrum(ms_out,2^16,48000,64,'MMS2');

    %% 模拟低通滤波器解调
    %clc;
    fprintf("正在执行模拟低通滤波\n");
    LPF = four_order_lpf_butterworth_filter();
    vout = filter(LPF,ms_out*vref*sdm_gain) ;
    whitenoise = GenerateWhiteNoise(-110,gwn_en,length(vout))';
    % plotCustomSpectrum_method2(whitenoise,param_cfg.raw_data_cfg.raw_fs,param_cfg.sdm.osr,"custom",'噪声输出 频谱图');
    %clc;
    fprintf("正在注入噪声\n");
    for i=1:interp_factor
        temparr1 = vout((i-1)*param_cfg.raw_data_cfg.pn + 1 :i*param_cfg.raw_data_cfg.pn);
        temparr2 = whitenoise((i-1)*param_cfg.raw_data_cfg.pn + 1 :i*param_cfg.raw_data_cfg.pn);
        vout((i-1)*param_cfg.raw_data_cfg.pn + 1 :i*param_cfg.raw_data_cfg.pn) = temparr2 + temparr1;
%         vout((i-1)*interp_factor + 1 :i*interp_factor) = vout((i-1)*interp_factor + 1 :i*interp_factor) + whitenoise((i-1)*interp_factor + 1 :i*interp_factor);
    end
    % vout = vout + whitenoise;

    % plotCustomSpectrum_method2(vout,param_cfg.raw_data_cfg.raw_fs,param_cfg.sdm.osr,"custom",'噪声输出 频谱图2');

    %% Sigma-Delta DAC 输出波形
    if(plot_en == "enable")
        raw_repelem_data = repelem(raw_data_buf, interp_factor);
        t = (0:interp_data_length-1) / (interp_factor * raw_fs);  % 时间轴（秒）
        % t1 = (0:interp_data_length-1)/fs_mod;
        figure;

        subplot(2,1,1);
        plot(t, bitstream,'b');
        xlabel('时间 (s)');
        ylabel('输出码流');
        legend('码流输出');
        title('Sigma-Delta DAC 1-bit 输出');

        subplot(2,1,2);
        plot(t, vout,'b'); hold on ;
        plot(t, interp_data(1:interp_data_length),'r');
        plot(t, raw_repelem_data(1:interp_data_length),'g--');
        xlabel('时间 (s)');
        ylabel('模拟输出幅度');
        legend('Sigma-Delta 滤波还原','原始值插值后输出','原始值');
        title('Sigma-Delta DAC 模拟 输出');
        % grid on;
    end
    %clc;
end



